package cn.edu.pzhu.servlet;

import java.io.IOException;
import java.sql.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import cn.edu.pzhu.pojo.FileMsg;
import cn.edu.pzhu.pojo.Msg;
import cn.edu.pzhu.pojo.User;
import cn.edu.pzhu.service.FileMsgService;
import cn.edu.pzhu.service.imp.FileMsgServiceImp;
import cn.pzhuweb.filesys.util.FileUtil;
import cn.pzhuweb.filesys.util.Result;

/**
 * Servlet implementation class UploadServlet
 */
@MultipartConfig
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		Part part = request.getPart("file");
		Result res =  FileUtil.uploadFile(part);
		HttpSession session =  request.getSession();
		String filename=request.getParameter("filename");
		String classification=request.getParameter("classification");
		String description=request.getParameter("description");
		String dateStr = request.getParameter("releasedate");
		Date releasedate = null;
		if (dateStr != null && !dateStr.isEmpty()) {
		    try {
		    	releasedate = Date.valueOf(dateStr);
		    } catch (IllegalArgumentException e) {
		    	session.setAttribute("msg", "请选择文件的公开时间！");
		    	session.setAttribute("msg1", "文件分享页面");
				session.setAttribute("url", "updateupload.jsp");
				response.sendRedirect("error.jsp");
				return;
		    }
		}
		String ratingStr = request.getParameter("rating");
		Double rating = null;
		if (ratingStr != null && !ratingStr.isEmpty()) {
		    try {
		        rating = Double.parseDouble(ratingStr);
		    } catch (NumberFormatException e) {
		    	session.setAttribute("msg", "请输入文件的评分！");
		    	session.setAttribute("msg1", "文件分享页面");
				session.setAttribute("url", "updateupload.jsp");
				response.sendRedirect("error.jsp");
				return;
		    }
		}
		
		if ("".equals(filename)) {// 文本框没有输入，结果是""
			session.setAttribute("msg", "请输入文件名！");
			session.setAttribute("msg1", "文件分享页面");
			session.setAttribute("url", "updateupload.jsp");
			response.sendRedirect("error.jsp");
			return;
		}
		
		try {
			User user = (User)request.getSession().getAttribute("user");
			String username = user.getUsername();
			FileMsg fm=new FileMsg(null,username,filename,classification,res.getData(),releasedate,rating,description);
			
			FileMsgService fs=new FileMsgServiceImp();
			Msg msg = fs.upload(fm);
			
			if(msg.isSuccess()) {
				System.out.println("数据库写入成功！");
			}else {
				System.out.println("数据库写入失败！");
			}
			
			if(res.isSuccess()) {
			    response.setContentType("text/html;charset=utf-8");
			    response.getWriter().print("<script>alert('上传成功，感谢您的分享!'); window.location.href='myshare.jsp';</script>");
			}else {
			    response.setContentType("text/html;charset=utf-8");
			    response.getWriter().print("<script>alert('上传失败，失败的原因是："+res.getMsg()+"!'); window.location.href='myshare.jsp';</script>");
			}
		} catch (Exception e) {
			session.setAttribute("msg", "请先登录再使用此功能！");	
			session.setAttribute("msg1", "登录页面");
			session.setAttribute("url", "login.jsp");
			response.sendRedirect("error.jsp");
			return; //流程结束，后续代码不需要再执行...
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
